package com.truba.ohostouchgallery.TouchView;

import ru.truba.touchgrallery.TouchView.InputStreamWrapper;

import java.io.*;

import com.truba.ohostouchgallery.Init;
import ohos.aafwk.ability.delegation.AbilityDelegatorRegistry;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.hiviewdfx.HiLog;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

public class InputStreamWrapperTest {

    private final Init init = new Init();
    private InputStreamWrapper inputStreamWrapper;

    @Before
    public void setUp() throws Exception {
        // 模拟跳转
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName("com.example.ohostouchgallery")
                .withAbilityName("com.example.ohostouchgallery.GalleryFileAbility")
                .build();
        intent.setOperation(operation);
        AbilityDelegatorRegistry.getAbilityDelegator().startAbilitySync(intent);

        InputStream inputStream = init.mContext.getResourceManager().getRawFileEntry("resources/rawfile/1.jpg").openRawFile();
        String path = init.mContext.getFilesDir() + "/" + ".jpg";
        File file = new File(path);
        copy(inputStream, file);
        FileInputStream fis = new FileInputStream(file);
        inputStreamWrapper = new InputStreamWrapper(fis, 8192, file.length());
    }

    @Test
    public void read() {
        byte[] buffer = new byte[1024];
        try {
            int num = inputStreamWrapper.read(buffer, 0, 5);
            assertEquals(5, num);
        } catch (IOException e) {
            HiLog.error(init.LABEL, e.getMessage());
        }

    }

    public void copy(InputStream in, File dst) throws IOException {

        OutputStream out = new FileOutputStream(dst);

        // Transfer bytes from in to out
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    }
}